package com.sasis.webapp;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.acegisecurity.providers.encoding.Md5PasswordEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.achievo.struts.ActionContext;
import com.sasis.Constants;
import com.sasis.model.CurrentUser;
import com.sasis.model.User;
import com.sasis.service.UserManager;

public class LoginServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3947192421637683644L;

	protected final Log log = LogFactory.getLog(getClass());

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(request.getSession()
						.getServletContext());

		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");

		log.debug("userName:" + username);
		log.debug("password:" + password);
		log.debug("loginservlet is here ");

		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		String encryptedPassword = encoder.encodePassword(password, null);

		UserManager umgr = (UserManager) ctx.getBean("userManager");
		User tempuser = umgr.getUser(username, encryptedPassword);
		if (tempuser == null) {
			request.getSession().setAttribute("loginflag", "false");
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/login.jsp");
			dispatcher.forward(request, response);
		} else {
			HttpSession session = request.getSession();
			session.setAttribute(Constants.CURUSER_KEY, "true");
			session.setAttribute("user", tempuser);
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/index.jsp");
			dispatcher.forward(request, response);
		}
	}

}
